#! /usr/bin/env bash

echo "[+] dresser setup"
echo ""


if [ "$DRESSER_HOME" == "" ]; then
  echo "DRESSER_HOME not defined, checking arg1"
  if [ "$1" == "" ]; then
    echo "DRESSER_HOME not passed as argument... Exiting"
    exit 1
  else
    DRESSER_HOME="$1"
  fi
fi
ddir="$DRESSER_HOME"

if [ ! -d "$ddir" ]; then
  echo "DRESSER_HOME directory does not exist"
  exit 1
fi

echo "$HOME"
if [[ "$HOME" == "" || "$HOME" == "/" ]]; then
  echo "Running as system"
  CFG_PATH=/etc
else
  CFG_PATH=$HOME/.dresser
  if [ -d "$HOME"/.dresser ]; then
    echo "$HOME/.dresser exists"
  else
    echo "Creating $HOME/.dresser"
    mkdir "$HOME"/.dresser
  fi
fi

echo "Fetching user data.."
USERDATA=`curl http://169.254.169.254/1.0/user-data`
echo "User data=$USERDATA"

HOSTNAME=`curl http://169.254.169.254/latest/meta-data/public-hostname`
echo "Hostname=$HOSTNAME"

echo "Creating dresser.cfg"
echo "DRESSER_HOME=$ddir" > $CFG_PATH/dresser.cfg
chmod 600 $CFG_PATH/dresser.cfg
echo $USERDATA | awk '{print "AWS_ACCESS_KEY_ID="$1; print "DRESSER_BUCKET="$3}' >> "$CFG_PATH"/dresser.cfg
echo "HOSTNAME=$HOSTNAME" >> "$CFG_PATH"/dresser.cfg
echo "# Add s3-bash options to the OPTS variable" >> "$CFG_PATH"/dresser.cfg
echo "OPTS=" >> "$CFG_PATH"/dresser.cfg

echo "Sourcing dresser.cfg"
source "$CFG_PATH"/dresser.cfg

echo "Creating aws.secret" 
AWS_SECRET=`echo $USERDATA | awk '{print $2}'`
echo $AWS_SECRET | tr -d "\n" > "$CFG_PATH"/aws.secret
chmod 600 $CFG_PATH/aws.secret
awsAccessSecretKeyIdFile="$CFG_PATH"/aws.secret
if [ ! -e "$awsAccessSecretKeyIdFile" ]; then
  echo "AWS Secret Key ID file does not exist in "$CFG_PATH""
  exit 1
fi

CWD=$PWD
echo "Working directory=$CWD"
cd /
MNT=/mnt
OUTFITDIR=outfit
DEST=$MNT/$OUTFITDIR
if [ ! -d $DEST ]; then
  echo "$DEST does not exist, creating"
  mkdir /mnt/outfit  
fi

OUTFIT=`echo $USERDATA | awk '{print $4}'`
echo "Outfit file=$OUTFIT"
FETCH_CMD="$ddir"/bin/d-get
echo "Fetching $OUTFIT"
$FETCH_CMD $OUTFIT > $OUTFIT
ENDLOOP=false

while [ "$ENDLOOP" == "false" ]
do 
  echo "Fetching outfit files" 
  for i in `cat $OUTFIT`
  do

    OUTFIT=""
    OUTPUTPATH=${i%/*}
    if [ ! -d $OUTPUTPATH ]; then
      echo "$OUTPUTPATH does not exist, skipping $i" 
    else
      echo "$FETCH_CMD $i > $i"
      $FETCH_CMD $i > $i
      if [ "${i##*.}" == "sh" ]; then
        chmod 750 $i
        $i
      else
        # Add additional handlers here
        case "${i##*.}" in
          outfit)
            OUTFIT=$i;
            ;;
          *)
            echo "No file handler for .${i##*.}";
            ;;
        esac
      fi
    fi
  done
  if [ "$OUTFIT" == "" ]; then
    ENDLOOP=true
  fi
done

cd $CWD

echo ""
echo "[+] dresser setup complete"
